package mcu.market.net;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Stack;

import org.apache.ibatis.exceptions.IbatisException;
import org.apache.ibatis.session.SqlSession;

import mcu.market.ibatis.IBatisFactory;
import mcu.market.ibatis.bean.BeanCompany;
import mcu.market.ibatis.bean.BeanDailyPrice;
import mcu.market.net.model.getPriceDataModel;
import mcu.market.net.model.getSwtDataModel;
import mcu.market.util.DateUtil;

public class getIPOPrice extends getPriceDataModel{
	SqlSession sqlSession;
	DateUtil du=new DateUtil();
	String init_date="2005-01-01";
	public getIPOPrice() {
		super.setCompanyList(super.IPO);
	}

	@Override
	public String getDataFromURL(Object parameter) {
		return null;
	}

	@Override
	public List paserData(String content, Object parameter) {
		String temp="";
		boolean k=false;
		ArrayList<String> al = new ArrayList();
		for(int i=0;i<content.length();i++){
				if(!String.valueOf(content.charAt(i)).equals(",")){
					temp=temp+String.valueOf(content.charAt(i));
				}else if((String.valueOf(content.charAt(i))+String.valueOf(content.charAt(i+1))).equals(",\"")){
					al.add(temp);
					temp="";
					i=i+2;
					while(!String.valueOf(content.charAt(i)).equals("\"")){
						temp=temp+String.valueOf(content.charAt(i));
						i++;
					}	
				}else{
					al.add(temp);
					temp="";
				}
				if(i==content.length()-1){
					al.add(temp);
					temp="";
				}
		}
		return al;
	}

	@Override
	public void insertDataToDB(List list, Object parameter) {
		
		if(list.size()>2){
			list.remove(0);
			list.remove(0);
			Stack<String> sk=(Stack<String>) list;
			//if(!sk.isEmpty()){sk.pop();sk.pop();}
			while(sk.isEmpty()==false){
				String str=sk.pop();
				String data[]=(String[]) paserData(str,null).toArray(new String[0]);
				if(data.length==0)break;
				BeanDailyPrice BDP= new BeanDailyPrice();
				try {				
					System.out.println(str);
					Double dp;
					BDP.setSid(((BeanCompany)parameter).getSid());
					BDP.setDay(du.convertTWDateToADDate(data[0]));
					BDP.setOpen((data[3].indexOf("-")>=0)?null:Double.parseDouble(data[3].replaceAll(",", "")));
					BDP.setHigh((data[4].indexOf("-")>=0)?null:Double.parseDouble(data[4].replaceAll(",", "")));
					BDP.setLow((data[5].indexOf("-")>=0)?null:Double.parseDouble(data[5].replaceAll(",", "")));
					BDP.setClose((data[6].indexOf("-")>=0)?null:Double.parseDouble(data[6].replaceAll(",", "")));
					BDP.setVolume(Long.parseLong(data[1].replaceAll(",", "")));
					BDP.setM_totle(Long.parseLong(data[2].replaceAll(",", "")));
					BDP.setM_count(Long.parseLong(data[8].replaceAll(",", "")));
					dp=(data[7].indexOf("X")>=0)?null:Double.parseDouble(data[7]);
					BDP.setD_price(dp);
					try{
						sqlSession.insert("daily_price.insertDailyPrice",BDP);
						sqlSession.commit();
					}catch(IbatisException e){
						if(!(e.getMessage().indexOf("duplicate key value violates")>=0)){
							sqlSession.close();
							sqlSession=IBatisFactory.getInstance().getSqlSession();
							
						}
						//e.printStackTrace();
					}
				} catch (ParseException e) {
					break;
				}
			}
		}
		
		
	}

	@Override
	public void execute() {
		Date d=checkData();
		String[] today = du.DateToString(d, "yyyy-MM-dd").split("-");
		List<BeanCompany> list=super.getCompanyList();
		
		for(BeanCompany bean:list){
			sqlSession=IBatisFactory.getInstance().getSqlSession();
			System.out.println("導入資料中"+"["+bean.getSid()+"]"+bean.getName());
			Date date =null;
			try{
				date =(Date) sqlSession.selectOne("daily_price.selectLastDay",bean);
			}catch(IbatisException e){
				sqlSession.close();
				sqlSession=IBatisFactory.getInstance().getSqlSession();
				Map map=new HashMap();
				map.put("sid", String.valueOf(bean.getSid()));
				map.put("sid_k", String.valueOf(bean.getSid()+"_pkey"));
				sqlSession.insert("daily_price.CreateDailyPrice",map);
				sqlSession.commit();}
			if(date==null){try{date=du.StringToDate(init_date, "yyyy-MM-dd");}catch(ParseException e){e.printStackTrace();}};
			String[] lastday = du.DateToString(date, "yyyy-MM-dd").split("-");
			//String urlstring = spliteYahooURL(lastday,today,String.valueOf(bean.getSid()));
			List<String> url_sk = spliteTransactionURL(lastday,today,String.valueOf(bean.getSid()));
			while(url_sk.isEmpty()==false){
				String url=url_sk.get(0);
				List<String> lt=getDailyPriceFromNet(url);
				insertDataToDB(lt, bean);
				url_sk.remove(0);
			}
			sqlSession.close();
		}
	}
	/**
	 * 拼出所有上市證交所的連結
	 * @param lastday
	 * @param today
	 * @param sid
	 * @return
	 */
	private static Stack<String> spliteTransactionURL(String[] lastday,String[] today,String sid) {
		//http://www.twse.com.tw/ch/trading/exchange/STOCK_DAY/STOCK_DAY_print.php?genpage=genpage/Report201310/201310_F3_1_8_1101.php&type=html
		String url_s="http://www.twse.com.tw/ch/trading/exchange/STOCK_DAY/STOCK_DAY_print.php?genpage=genpage/Report";
		String url_m="_F3_1_8_";
		String url_l=".php&type=csv";
		Stack<String> stack =new Stack<String>();
		int l_y=Integer.parseInt(lastday[0]);
		int l_m=Integer.parseInt(lastday[1]);
		int t_y=Integer.parseInt(today[0]);
		int t_m=Integer.parseInt(today[1]);
		String check=String.valueOf(t_y)+String.format("%02d", t_m);
		String url="";
		while(!check.equals(url)){
			url=String.valueOf(l_y)+String.format("%02d", l_m);
			if(l_m<=12){
				stack.add(url_s+url+"/"+url+url_m+sid+url_l);
				l_m++;
			}else if(l_m>12){
				l_m=1;
				l_y++;
			}
		};
		return stack;
	}
	/**
	 * 讀取URL下載資料(設定為CSV),資料斷行為分隔堆疊成STACK
	 * @param urlstring
	 * @return
	 */
	private static Stack<String> getDailyPriceFromNet(String urlstring) {
		Stack<String> sk=new Stack<String>();
		try {
			URL url = new URL(urlstring);
			URLConnection connection = url.openConnection();
			InputStream in = connection.getInputStream();
			InputStreamReader is = new InputStreamReader(in,"big5");
			StringBuilder sb=new StringBuilder();
			BufferedReader br = new BufferedReader(is);
			String read = br.readLine();
			
			while(read != null) {
				sk.push(read);
				//String data[]=read.toString().split(",");
			    //System.out.println(read);
			    read =br.readLine();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return sk;
	}
}
